<?php

function smarty_modifier_filter($name) {
    $context = ModulesContext::instance();
    $session = $context->getSession();

    if ($session->state() == SessionStates::ACTIVE) {
        $filters = array_slice(func_get_args(), 1);

        $filterList = $session->get("__filters", array());

        if (is_array($filters) && count($filters) > 0) {
            $filterList[$name] = array();

            foreach ($filters as $filter) {
                $result = resolveNameAndParams($filter);
                $filterList[$name][] = $result;
            }

            $session->put("__filters", $filterList);
        }
    }

    return $name;
}

function resolveNameAndParams($name) {

    $firstParenthesis = strpos($name, "(");
    $realName = $name;
    //If function has arguments
    if ($firstParenthesis !== false) {
        $realName = substr($name, 0, $firstParenthesis);
        $lastParenthesis = strrpos($name, ")");
        $paramsString = substr($name, $firstParenthesis);
        $params = preg_split("/(',\s*')/", rtrim($paramsString, ")"));
    }

    $parameters = array();

    if (isset($params) && is_array($params)) {
        $parameters = $params;
    }

    return array("name" => $realName, "params" => $parameters,);
}

?>
